"""
未来模型兼容性配置
支持新发布的AI模型和提供商
"""

from typing import Dict, List, Any
import logging

logger = logging.getLogger(__name__)


class FutureModelsConfig:
    """未来模型兼容性配置类"""
    
    @staticmethod
    def get_future_model_patterns() -> Dict[str, List[str]]:
        """获取未来模型的命名模式"""
        return {
            "openai": [
                r"gpt-4o-\d{4}-\d{2}-\d{2}",  # GPT-4o系列: gpt-4o-2024-12-17
                r"gpt-5.*",                    # GPT-5系列
                r"o1-.*",                      # o1系列: o1-preview, o1-mini
                r"gpt-4-turbo-\d{4}-\d{2}-\d{2}",  # GPT-4 Turbo新版本
            ],
            "doubao": [
                r"doubao-seed-\d+\.\d+-.*",   # Seed系列: doubao-seed-1.6-flash-250615
                r"doubao-\d+-\d+-.*",         # 新版本格式: doubao-2-0-pro-32k
                r"Doubao-.*",                 # 首字母大写格式
                r"doubao-.*-\d{6}",          # 带日期的模型: doubao-xxx-250615
            ],
            "claude": [
                r"claude-3-.*-\d{8}",         # Claude 3系列新版本
                r"claude-4-.*",               # Claude 4系列
                r"claude-.*-v\d+",            # 版本号格式
            ],
            "gemini": [
                r"gemini-\d+\.\d+-.*",        # Gemini版本号格式
                r"gemini-ultra.*",            # Gemini Ultra系列
                r"gemini-nano.*",             # Gemini Nano系列
            ],
            "zhipu": [
                r"glm-\d+.*",                 # GLM系列: glm-4, glm-5
                r"chatglm.*",                 # ChatGLM系列
                r"codegeex.*",                # CodeGeeX系列
            ],
            "deepseek": [
                r"deepseek-chat-v\d+",        # 版本号格式
                r"deepseek-coder-v\d+",       # Coder系列
                r"deepseek-.*-\d{4}-\d{2}",   # 带日期格式
            ]
        }
    
    @staticmethod
    def get_emerging_providers() -> Dict[str, Dict[str, Any]]:
        """获取新兴AI提供商配置"""
        return {
            "moonshot": {
                "name": "月之暗面",
                "description": "Kimi大模型",
                "default_url": "https://api.moonshot.cn/v1/chat/completions",
                "default_model": "moonshot-v1-128k",
                "openai_compatible": True
            },
            "baichuan": {
                "name": "百川智能",
                "description": "百川大模型",
                "default_url": "https://api.baichuan-ai.com/v1/chat/completions",
                "default_model": "Baichuan2-Turbo",
                "openai_compatible": True
            },
            "minimax": {
                "name": "MiniMax",
                "description": "MiniMax大模型",
                "default_url": "https://api.minimax.chat/v1/text/chatcompletion_pro",
                "default_model": "abab6.5s-chat",
                "openai_compatible": False  # 需要特殊适配器
            },
            "qwen": {
                "name": "通义千问",
                "description": "阿里云通义千问",
                "default_url": "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
                "default_model": "qwen-turbo",
                "openai_compatible": False  # 需要特殊适配器
            },
            "spark": {
                "name": "讯飞星火",
                "description": "科大讯飞星火大模型",
                "default_url": "https://spark-api.xf-yun.com/v1/chat/completions",
                "default_model": "spark-3.5",
                "openai_compatible": True
            },
            "yi": {
                "name": "零一万物",
                "description": "Yi系列大模型",
                "default_url": "https://api.lingyiwanwu.com/v1/chat/completions",
                "default_model": "yi-34b-chat",
                "openai_compatible": True
            },
            "step": {
                "name": "阶跃星辰",
                "description": "Step系列大模型",
                "default_url": "https://api.stepfun.com/v1/chat/completions",
                "default_model": "step-1v-32k",
                "openai_compatible": True
            }
        }
    
    @staticmethod
    def is_future_model(provider: str, model: str) -> bool:
        """检查是否为未来模型"""
        import re
        
        patterns = FutureModelsConfig.get_future_model_patterns()
        provider_patterns = patterns.get(provider.lower(), [])
        
        for pattern in provider_patterns:
            if re.match(pattern, model):
                logger.info(f"识别到未来模型: {provider}/{model}")
                return True
        
        return False
    
    @staticmethod
    def get_provider_config(provider: str) -> Dict[str, Any]:
        """获取提供商配置"""
        emerging = FutureModelsConfig.get_emerging_providers()
        return emerging.get(provider.lower(), {})
    
    @staticmethod
    def is_openai_compatible(provider: str) -> bool:
        """检查提供商是否OpenAI兼容"""
        config = FutureModelsConfig.get_provider_config(provider)
        return config.get("openai_compatible", True)  # 默认假设兼容
    
    @staticmethod
    def get_auto_detection_rules() -> Dict[str, List[str]]:
        """获取自动检测规则"""
        return {
            "api_url_patterns": [
                r".*openai.*",           # OpenAI相关
                r".*anthropic.*",        # Claude相关
                r".*google.*",           # Google相关
                r".*deepseek.*",         # DeepSeek相关
                r".*moonshot.*",         # 月之暗面
                r".*baichuan.*",         # 百川智能
                r".*minimax.*",          # MiniMax
                r".*aliyun.*",           # 阿里云
                r".*xf-yun.*",           # 讯飞
                r".*lingyiwanwu.*",      # 零一万物
                r".*stepfun.*",          # 阶跃星辰
            ],
            "model_name_hints": [
                ("gpt", "openai"),
                ("claude", "claude"),
                ("gemini", "gemini"),
                ("doubao", "doubao"),
                ("glm", "zhipu"),
                ("moonshot", "moonshot"),
                ("baichuan", "baichuan"),
                ("qwen", "qwen"),
                ("spark", "spark"),
                ("yi", "yi"),
                ("step", "step"),
            ]
        }
    
    @staticmethod
    def auto_detect_provider(api_url: str, model: str) -> str:
        """自动检测提供商"""
        import re
        
        rules = FutureModelsConfig.get_auto_detection_rules()
        
        # 1. 通过API URL检测
        for pattern in rules["api_url_patterns"]:
            if re.search(pattern, api_url.lower()):
                # 提取提供商名称
                for keyword in ["openai", "anthropic", "google", "deepseek", 
                               "moonshot", "baichuan", "minimax", "aliyun", 
                               "xf-yun", "lingyiwanwu", "stepfun"]:
                    if keyword in api_url.lower():
                        provider_map = {
                            "anthropic": "claude",
                            "google": "gemini",
                            "aliyun": "qwen",
                            "xf-yun": "spark",
                            "lingyiwanwu": "yi",
                            "stepfun": "step"
                        }
                        return provider_map.get(keyword, keyword)
        
        # 2. 通过模型名称检测
        for hint, provider in rules["model_name_hints"]:
            if hint in model.lower():
                return provider
        
        # 3. 默认返回自定义提供商
        logger.info(f"无法自动检测提供商，使用通用适配器: {api_url}")
        return "custom"
    
    @staticmethod
    def get_compatibility_info() -> Dict[str, Any]:
        """获取兼容性信息"""
        return {
            "supported_formats": [
                "OpenAI Chat Completions API",
                "Google Gemini API",
                "Anthropic Claude API",
                "Custom REST API"
            ],
            "auto_features": [
                "JSON格式自动检测",
                "错误重试机制",
                "响应格式验证",
                "提供商自动识别"
            ],
            "extensibility": [
                "通用适配器支持",
                "动态模型注册",
                "自定义提供商配置",
                "未来模型模式匹配"
            ]
        }


# 全局实例
future_models = FutureModelsConfig()
